<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button class="filter-item" type="primary" icon="el-icon-refresh" @click="handleRefresh">
        刷新
      </el-button>
      <el-input v-model="listQuery.searchMsg" placeholder="搜索名称" style="width: 200px;" class="filter-item filter-input"
                @keyup.enter.native="handleFilter"/>
      <el-button style="margin-left: 10px;" class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item add" style="margin-left: 10px;margin-right: 10px" type="primary" icon="el-icon-circle-plus-outline"
                 @click="handleCreate">
        添加
      </el-button>

    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row

    >
      <el-table-column
        type="index"
        label="序号"
        align="center"
        width="50">
      </el-table-column>
      <!-- <el-table-column align="center" label="ID" width="95" >
        <template slot-scope="scope">
          {{ scope.row.Index }}
        </template>
      </el-table-column> -->

      <el-table-column label="名称" width="230" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>



      <el-table-column label="病人信息" align="center">
        <template slot-scope="scope">
          <span>{{ truncatedText(scope.row.caseJson) }}</span>

        </template>
      </el-table-column>

      <el-table-column label="详细信息" align="center">
        <template slot-scope="scope">
          <span>{{ truncatedText(scope.row.itemJson) }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" prop="created_at" label="创建时间" width="200">
        <template slot-scope="scope">
          <i class="el-icon-time"/>
          <span>{{ scope.row.createdAt }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="updated_at" label="更新时间" width="200">
        <template slot-scope="scope">
          <i class="el-icon-time"/>
          <span>{{ scope.row.updatedAt }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
                @pagination="fetchData"/>

    <el-dialog :title="title" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
      <el-form ref="dataForm" :model="Form" label-position="left" label-width="90px"
      >

        <el-form-item label="名称" prop="username">
          <el-input v-model="Form.name"/>
        </el-form-item>

        <el-form-item label="设备" prop="username">
          <el-select v-model="Form.device" clearable placeholder="请选择" @change="handleChangeDI">
            <el-option
              v-for="item in listOptions(deviceMsg)"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              @click.native.stop="selectDi( item.value,item.label)">
            </el-option>
          </el-select>
        </el-form-item>

        <!--<el-form-item label="描述" prop="name">-->
        <!--<el-input v-model="Form.note"/>-->
        <!--</el-form-item>-->
        <div class="jsonBox">
          <div>
            <span>病人信息</span>
          </div>
          <el-row v-for="(item, index) in caseJson.caseValue" :key="index">
            <el-col :span="6" style="padding-right: 10px;padding-left: 10px">
              <div class="sub-title">信息名称</div>
              <el-autocomplete
                class="inline-input"
                v-model="item.name"
                :fetch-suggestions="querySearch"
                placeholder="请输入内容"
                @select="(selectedItem) => handleSelect(selectedItem, index)"
              >
                <!-- 使用 render-item 插槽自定义下拉列表项 -->
                <template slot-scope="{ item: suggestion }">
                  <div>{{ suggestion.name }}</div>  <!-- 显示 name 字段 -->
                </template>
              </el-autocomplete>
            </el-col>
            <el-col :span="9" style="padding-right: 10px;">
              <div class="sub-title">默认值</div>
              <el-input  v-model="item.value" placeholder="请输入内容"></el-input>
            </el-col>
            <el-col :span="6" style="padding-right: 10px;padding-left: 10px">
              <div class="sub-title">值类型</div>
              <el-autocomplete
                class="inline-input"
                v-model="item.valueType"
                :fetch-suggestions="typeSearch"
                placeholder="请输入内容"
                @select="(selectedItem) => typeSelect(selectedItem, index)"
              >

              </el-autocomplete>
            </el-col>
            <el-col :span="3" style="padding-right: 10px;padding-left: 10px">
              <div class="sub-title">操作</div>
              <el-button size="mini" type="danger" @click="delCaseList(index)">
                删除
              </el-button>
            </el-col>
          </el-row>
          <div class="addBox">
            <el-button @click="addCaseList" type="primary" icon="el-icon-plus"></el-button>
          </div>
        </div>
        <div class="jsonBox">
          <div>
            <span>详细信息</span>
          </div>
          <el-row v-for="(item, index) in itemJson.itemValue" :key="index">
            <el-col :span="6" style="padding-right: 10px;padding-left: 10px">
              <div class="sub-title">信息名称</div>
              <el-autocomplete
                class="inline-input"
                v-model="item.name"
                :fetch-suggestions="itemListSearch"
                placeholder="请输入内容"
                @select="(selectedItem) => itemListSelect(selectedItem, index)"
              >
                <!-- 使用 render-item 插槽自定义下拉列表项 -->
                <template slot-scope="{ item: suggestion }">
                  <div>{{ suggestion.name }}</div>  <!-- 显示 name 字段 -->
                </template>
              </el-autocomplete>
            </el-col>
            <el-col :span="9" style="padding-right: 10px;">
              <div class="sub-title">默认值</div>
              <el-input  v-model="item.value" placeholder="请输入内容"></el-input>
            </el-col>
            <el-col :span="6" style="padding-right: 10px;padding-left: 10px">
              <div class="sub-title">值类型</div>
              <el-autocomplete
                class="inline-input"
                v-model="item.valueType"
                :fetch-suggestions="typeSearch"
                placeholder="请输入内容"
                @select="(selectedItem) => itemtypeSelect(selectedItem, index)"
              >

              </el-autocomplete>
            </el-col>
            <el-col :span="3" style="padding-right: 10px;padding-left: 10px">
              <div class="sub-title">操作</div>
              <el-button size="mini" type="danger" @click="delItemList(index)">
                删除
              </el-button>
            </el-col>
          </el-row>
          <div class="addBox">
            <el-button @click="addItemList" type="primary" icon="el-icon-plus"></el-button>
          </div>
        </div>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          提交
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import Pagination from '@/components/Pagination' // secondary package based on el-pagination
  import {
    IgsOrgansAPI
  } from '../../../../api/igs/organs'
  import {IgsConfigAPI} from '../../../../api/igs/igsConfig'
  import {IgsDeviceAPI} from '../../../../api/igs/device'
  export default {
    filters: {
      statusFilter(status) {
        const statusMap = {
          published: 'success',
          draft: 'gray',
          deleted: 'danger'
        }
        return statusMap[status]
      }
    },
    components: {Pagination},
    name: 'user',
    data() {

      return {
        list: null,
        listLoading: true,
        total: 0,
        listQuery: {
          page: 1,
          limit: 10,
          searchMsg: '',
          orderby:'ORDER BY `id` DESC'
        },
        dialogFormVisible: false,
        dialogStatus: "create",
        title: "",

        Form: {
          id: null,
          name: '',
          node: '',
          pid:0,
          device:'',
          caseJson: {
            caseValue:[{
              id: '',
              name: '',
              value: '',
              valueType: ''
            }]
          },
          itemJson: {
            itemValue:[{
              id: '',
              name: '',
              value: '',
              valueType: ''
            }]
          }

        },
        roles: null,
        caseJson: {
          caseValue:[]
        },
        itemJson: {
          itemValue:[]
        },
        caseList: null,
        itemList: null,
        typeValues: [
          {value: '文本'},
          {value: '数字'},
          {value: '时间'},
          {value: '日期'},
          {value: '单选'},
          {value: '多选'}
        ],
        addJson: {
          id: '',
          name: '',
          value: '',
          valueType: ''
        },
        deviceMsg:[],
        selectdeviceMsg: null,
      }
    },
    created() {
      this.fetchData()
    },
    methods: {
      handleChangeDI(value) {
        if (!value) {
          this.selectdeviceMsg = null
        }
      },
      listOptions(list) {

        return list.map(item => ({
          value: item.id,
          label: item.name
        }));

      },
      selectDi(id, name) {
        // console.log('Selected id:', id);
        // console.log('Selected name:', name);
        this.Form.device = name;
        this.Form.pid = id;
        console.log('deviceMsg:', this.deviceMsg);


      },


      addItemList() {
        console.log('in to addItemList');
        // 使用 Vue.set 或 this.$set 来添加对象并确保它是响应式的
        this.$set(this.itemJson.itemValue, this.itemJson.itemValue.length, (JSON.parse(JSON.stringify(this.addJson))));
        console.log(this.itemJson);
      },
      addCaseList() {
        console.log('in to addCaseList');
        // 使用 Vue.set 或 this.$set 来添加对象并确保它是响应式的
        this.$set(this.caseJson.caseValue, this.caseJson.caseValue.length, (JSON.parse(JSON.stringify(this.addJson))));
        console.log(this.caseJson);
      },
      delItemList(index) {
        console.log('in to delItemList');


        this.$confirm('是否确定删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          if (index >= 0 && index < this.itemJson.itemValue.length) {
            this.itemJson.itemValue.splice(index, 1); // 第一个参数是起始位置，第二个参数是要删除的项数
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
          } else {
            this.$message({
              type: 'warning',
              message: '无效的索引!'
            });
          }

        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });

        console.log("this.itemJson.itemValue:", this.itemJson);
      },
      delCaseList(index) {
        console.log('in to delCaseList');


        this.$confirm('是否确定删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          if (index >= 0 && index < this.caseJson.caseValue.length) {
            this.caseJson.caseValue.splice(index, 1); // 第一个参数是起始位置，第二个参数是要删除的项数
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
          } else {
            this.$message({
              type: 'warning',
              message: '无效的索引!'
            });
          }

        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });

        console.log("this.caseJson:", this.caseJson);
      },
      typeSearch(queryString, cb) {
        let restaurants = this.typeValues;
        // console.log('restaurants', restaurants);
        let results = queryString ? restaurants.filter(this.typeFilter(queryString)) : restaurants;
        // 调用 callback 返回建议列表的数据
        // console.log('results', results);
        cb(results);
      },
      typeFilter(queryString) {
        return (restaurant) => {
          // console.log('restaurant',restaurant);
          return (restaurant.value.indexOf(queryString) === 0);
        };
      },
      itemListSearch(queryString, cb) {
        let restaurants = this.itemList;
        // console.log('restaurants', restaurants);
        let results = queryString ? restaurants.filter(this.itemListFilter(queryString)) : restaurants;
        // 调用 callback 返回建议列表的数据
        // console.log('results', results);
        cb(results);
      },
      itemListFilter(queryString) {
        return (restaurant) => {
          // console.log('restaurant',restaurant);
          return (restaurant.name.indexOf(queryString) === 0);
        };
      },

      querySearch(queryString, cb) {
        let restaurants = this.caseList;
        // console.log('restaurants', restaurants);
        let results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
        // 调用 callback 返回建议列表的数据
        // console.log('results', results);
        cb(results);
      },
      createFilter(queryString) {
        return (restaurant) => {
          // console.log('restaurant',restaurant);
          return (restaurant.name.indexOf(queryString) === 0);
        };
      },
      itemListSelect(item, index) {
        console.log('Selected item:', item);
        console.log('Index of selected item:', index);
        console.log('this.itemList.itemValue:', this.itemJson);
        this.$set(this.itemJson.itemValue, index, (JSON.parse(JSON.stringify(item))));
        console.log('itemJson:', this.itemJson);
      },
      handleSelect(item, index) {
        console.log('Selected item:', item);
        console.log('Index of selected item:', index);
        // 使用 $set 确保响应式更新
        this.$set(this.caseJson.caseValue, index, (JSON.parse(JSON.stringify(item))));
        console.log('this.caseJson.caseValue:', this.caseJson);
      },
      typeSelect(item, index) {
        console.log('Selected item:', item);
        console.log('Index of selected item:', index);
        this.caseJson.caseValue[index].valueType = JSON.parse(JSON.stringify(item.value))
        console.log('this.caseJson.caseValue:', this.caseJson.caseValue);
      },
      itemtypeSelect(item, index) {
        console.log('itemtypeSelect item:', item);
        console.log('Index of selected item:', index);
        this.itemJson.itemValue[index].valueType = JSON.parse(JSON.stringify(item.value))
        console.log('this.itemJson.itemValue:', this.itemJson.itemValue);
      },
      truncatedText(longText) {
        return longText.length > 30 ? longText.slice(0, 30) + '...' : longText;
      },

      fetchData() {
        this.listLoading = true
        IgsOrgansAPI.hasAllToPage(this.listQuery).then(response => {
          let list = response.data.list
          const data = list
          this.list = data
          this.total = response.data.queryTotal
          this.listQuery.page = response.data.page
          setTimeout(() => {
            this.listLoading = false
          }, 0.3 * 1000)
        })
        let da = {
          type: 1
        }
        IgsConfigAPI.hasAllByType(da).then(res => {
          this.caseList = res.data;

        })
        da = {
          type: 0
        }
        IgsConfigAPI.hasAllByType(da).then(res => {
          this.itemList = res.data;
        })
        da = {
          type: 0
        }
        IgsDeviceAPI.hasAll(da).then(res => {
          this.deviceMsg = res.data;
        })
      },

      handleFilter() {
        //搜索
        this.listQuery.page = 1
        this.listQuery.searchMsg = this.listQuery.searchMsg.trim()
        this.fetchData()
      },
      handleCreate() {
        //新增
        console.log('in to handleCreate');
        this.title = "添加"
        this.dialogStatus = 'create'
        this.Form = {
          id: null,
          name: '',
          node: '',
          pid:0,
          device:'',
          caseJson: {
            caseValue:[]
          },
          itemJson: {
            itemValue:[{
              id: '',
              name: '',
              value: '',
              valueType: ''
            }]
          }
        }
        console.log('in to this.caseList',this.caseList);
        // this.caseJson.caseValue = this.caseList.slice();
        //复制
        this.caseJson.caseValue = JSON.parse(JSON.stringify(this.caseList));
        this.itemJson.itemValue=[{
          id: '',
          name: '',
          value: '',
          valueType: ''
        }]
        console.log('this.Form',this.Form);
        this.dialogFormVisible = true
        // setTimeout(() => {
        //   this.$refs['dataForm'].clearValidate();
        // }, 300)
      },
      handleUpdate(row) {
        console.log('in to handleUpdate');
        //编辑
        this.dialogFormVisible = true
        this.title = "修改"
        this.dialogStatus = 'update'
        this.Form = {
          id: row.id,
          name: row.name,
          node: row.node,
          caseJson: row.caseJson,
          itemJson: row.itemJson,
          pid:row.pid,
          device:row.device,

        }

        // 使用JSON.parse()来解析字符串为JSON对象
        this.caseJson = JSON.parse(row.caseJson);
        this.itemJson = JSON.parse(row.itemJson);

        console.log(this.caseJson)
        console.log(this.itemJson)
        console.log(this.Form)
      },
      handleDelete(row, index) {
        //删除
        this.$confirm('确认删除？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          IgsOrgansAPI.delete({id: row.id}).then(() => {
            this.$notify({
              title: 'Success',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            this.list.splice(index, 1)
          })
        }).catch(() => {
        });
      },
      handleRefresh() {
        //列表刷新
        this.fetchData()
      },
      handleStatus(row) {
        //更改状态
        console.log(row)
      },
      createData() {
        console.log('in to updateData');
        console.log('this.Form', this.Form);
        console.log('this.caseJson', this.caseJson);
        console.log('this.itemJson', this.itemJson);
        // 将对象转换为JSON字符串
        let str = JSON.stringify(this.caseJson);
        this.Form.caseJson=str;
        str = JSON.stringify(this.itemJson);
        this.Form.itemJson=str;
        console.log('this.Form', this.Form);
        if(this.Form.pid<1){

          this.$message.error('请选择设备');
        }else {
          IgsOrgansAPI.add(this.Form).then(() => {
            this.fetchData()
            this.dialogFormVisible = false
          })
        }

      },
      updateData() {
        console.log('in to updateData');
        console.log('this.Form', this.Form);
        console.log('this.caseJson', this.caseJson);
        console.log('this.itemJson', this.itemJson);
        // 将对象转换为JSON字符串
        let str = JSON.stringify(this.caseJson);
        this.Form.caseJson=str;
        str = JSON.stringify(this.itemJson);
        this.Form.itemJson=str;
        console.log('this.Form', this.Form);
        if(this.Form.pid<1){

          this.$message.error('请选择设备');
        }else {
          IgsOrgansAPI.update(this.Form).then(() => {
            this.fetchData()
            this.dialogFormVisible = false
          })
        }

      }
    }
  }
</script>
<style lang="scss" scoped>
  .filter-container {
    .filter-item {
      margin-bottom: 10px;
    }
    .filter-input {
      margin-left: 20px;
    }
    .add {
      float: right;
    }
  }

  .addBox {
    width: 100%;
    button {
      width: 300px;
      margin: 10px auto;
      position: relative;
      display: block;
    }
  }
</style>
